#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 510, INF = 0x3f3f3f3f;

struct node
{
    int x, y, st, step;
};
int n, m;
pair<int, int> star, goal;
bool vis[N][N][2];
char mp[N][N];
int d[4][2] = { 1,0,-1,0,0,1,0,-1 };

bool check(node nx)
{
    if (nx.x >= 1 && nx.x <= n && nx.y >= 1 && nx.y <= m && vis[nx.x][nx.y][nx.st] == 0) {
        if (mp[nx.x][nx.y] == '?') nx.st = !nx.st;
        if (mp[nx.x][nx.y] == '#' ||
            (nx.st == 0 && mp[nx.x][nx.y] == 'x') ||
            (nx.st == 1 && mp[nx.x][nx.y] == 'o')) return 0;
        else return 1;
    } else return 0;
}

int bfs(pair<int, int> t) {
    queue<node> q;
    q.push({ t.first, t.second, 0, 0 }); // 初始门状态 0
    vis[t.first][t.second][0] = 1;

    while (!q.empty()) {
        node now = q.front(); q.pop();

        if (make_pair(now.x, now.y) == goal) return now.step;

        for (int i = 0; i < 4; i++) {
            int nx = now.x + d[i][0];
            int ny = now.y + d[i][1];
            int ns = now.st;
            int nstep = now.step + 1;

            // 越界
            if (nx < 1 || nx > n || ny < 1 || ny > m) continue;

            // 判断能不能走
            char c = mp[nx][ny];
            if (c == '#') continue;
            if (ns == 0 && c == 'x') continue;
            if (ns == 1 && c == 'o') continue;

            // 遇到开关翻转
            if (c == '?') ns ^= 1;

            if (!vis[nx][ny][ns]) {
                vis[nx][ny][ns] = 1;
                q.push({ nx, ny, ns, nstep });
            }
        }
    }
    return -1;
}


void solve()
{
    cin >> n >> m;
    for (int i = 1;i <= n;i++)
        for (int j = 1;j <= m;j++) {
            cin >> mp[i][j];
            if (mp[i][j] == 'S') star = { i,j };
            if (mp[i][j] == 'G') goal = { i,j };
        }

    cout << bfs(star);
}

signed main()
{
    //ios::sync_with_stdio(0);
    //cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    //cin>>T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}